﻿using Ebusiness_Framework.DistributedAuthorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using OpenIddict.Validation.AspNetCore;
using Polly;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Distributed_AuthenticationService.DistributedAuthorization
{
    public static class OpeniddictValidationServiceCollectionExtentions
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static IServiceCollection AddOpeniddictValidationDistributedAuthorization(this IServiceCollection services, IConfiguration configuration)
        {
            //开启身份验证【Token】
            services.AddAuthentication(options =>
            {
                options.DefaultScheme = OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme;
            });

            OpeniddictValidation distributedAuthorizationOptions = configuration.GetSection("OpeniddictValidationAuthorization").Get<OpeniddictValidation>();
            services.AddOpenIddict()
                            .AddValidation(options =>
                            {
                                options.SetIssuer(distributedAuthorizationOptions.Authority); // 权限服务地址
                                options.UseSystemNetHttp();
                                options.UseAspNetCore();
                                // 设置受众
                                // 1、默认一个Token访问一个微服务
                                options.AddAudiences(distributedAuthorizationOptions.Audience);
                                // 2、如果希望多个Token访问一个微服务
                                //options.AddAudiences("ProductService", "AlertService");
                            });
            return services;
        }
    }
}
